const mysql = require('mysql');

class MySQLDb {
  constructor(host, user, password, database) {
    this.host = host;
    this.user = user;
    this.password = password;
    this.database = database;
    this.pool = this.getPool(500);
  }

  getPool(size) {
    return mysql.createPool({
      connectionLimit: size,
      acquireTimeout: 100000,
      host: this.host,
      user: this.user,
      password: this.password,
      database: this.database
    });
  }

  insertData(insertSql, items, callback) {
    this.pool.query(insertSql, [items], function (err, rows, fields) {
      if (err) {
        console.log('INSERT ERROR - ', err.message);
        return;
      }
      if (callback) {
        callback();
      }
    });
  }

  insertCityranks(cityranks, callback) {
    let insertSql = "insert into cityrank(`id`, `dt`, `name`, `type`, `date`, `content`) values ?";
    this.insertData(insertSql, cityranks, callback);
  }

  insertProvinceranks(ranks, callback) {
    let insertSql = "insert into provincerank(`id`, `dt`, `name`, `type`, `date`, `content`) values ?";
    this.insertData(insertSql, ranks, callback);
  }

  insertHistories(histories, callback) {
    let insertSql = "insert into historyCurve(`id`, `dt`, `name`, `type`, `startDate`, `endDate`, `content`) values ?";
    this.insertData(insertSql, histories, callback);
  }
}

exports.MySQLDb = MySQLDb;